import { MessageType, type MessageData } from "./MessageData";

export class SignalingClient {
    private server: WebSocket | null = null;
    private can: boolean = true;
    public removeHand = (peerId: string) => { }
    private timer: number | undefined;
    constructor(
        private url: string,
        private path: string,
        private userid: string,
        private heander?: string | string[]
    ) { }

    connect(): Promise<void> {
        return new Promise((resolve, reject) => {
            if (!this.server || this.can) {

                this.can = false;
                const url = this.url + "/" + this.path + "?id=" + this.userid
                this.server = new WebSocket(url, this.heander)
                this.server.onopen = () => {
                    resolve();
                    this.can = false;
                    if (!this.timer) {
                        this.timer = setInterval(() => {
                            this.send({ type: MessageType.active })
                        }, 5000)
                    }
                };
                this.server.onerror = (err) => {
                    reject(err);
                    this.server = null;
                    this.can = true;
                    clearInterval(this.timer)
                };
            }
        });
    }
    delRemote = (peerId: string) => {
        console.log("移除远端",peerId);
        this.removeHand(peerId)
    }
    close = () => {
        if (this.server && this.server.readyState == WebSocket.OPEN) {
            this.server.close()
            this.server = null;
            this.can = true;
            clearInterval(this.timer)
        }
    }
    onClose = (callback: (e: CloseEvent) => void) => {
        if (this.server) {
            this.server.onclose = (e: CloseEvent) => {
                clearInterval(this.timer)
                this.can = true;
                this.delRemote(this.userid)
                this.send({ type: MessageType.bye })
                callback(e)
            }
        }
    }
    onMessage = (callback: (message: MessageData) => void) => {
        if (this.server) {
            this.server.onmessage = (e: MessageEvent) => {
                callback(JSON.parse(e.data))
            }
        }
    }
    send = ({
        type = MessageType.msg,
        to = "",
        sender = this.userid,
        data,
        ext
    }: MessageData): Promise<void> => {
        return new Promise((resolve, reject) => {
            if (!type || !sender) {
                return reject(new Error("参数 'type' 和 'sender' 是必需的"));
            }
            if (!this.server) {
                return reject(new Error("WebSocket 未初始化"));
            }
            if (this.server.readyState !== WebSocket.CLOSED &&
                this.server.readyState !== WebSocket.CLOSING) {
                try {
                    this.server.send(JSON.stringify({ type, to, sender, data, ext }));
                    resolve();
                } catch (err) {
                    reject(err)
                }
            } else {
                reject("消息发送失败,连接可能已经关闭")
            }
        })
    }
}